package com.yellow.car.task;

import com.yellow.car.api.StationApi;
import com.yellow.car.api.YellowCarApi;
import com.yellow.car.entity.CyclingYellowCar;
import com.yellow.car.entity.Station;
import com.yellow.car.request.YellowCarCyclingRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@EnableScheduling
@Slf4j
public class YellowCarTask {
    @Resource
    YellowCarApi yellowCarApi;
    @Resource
    StationApi stationApi;

    @Scheduled(cron = "0/1 * * * * ?")
    private void yellowCar() {
        log.info("小黄车模拟用户骑行任务开始");
        Station startStation = getStation(null);
        Station endStation = getStation(startStation);
        YellowCarCyclingRequest yellowCarCyclingRequest = new YellowCarCyclingRequest();
        yellowCarCyclingRequest.setStartStationName(startStation.getStationName());
        yellowCarCyclingRequest.setEndStationName(endStation.getStationName());
        yellowCarApi.cycling(yellowCarCyclingRequest);
    }

    @Scheduled(cron = "0/1 * * * * ?")
    private void cyclingEndYellowCar() {
        log.info("检查路途中的小黄车是否结束骑行");
        List<CyclingYellowCar> cyclingEndCarList = yellowCarApi.getCyclingCar();
        if (CollectionUtils.isEmpty(cyclingEndCarList)) {
            return;
        }
        long currentTime = System.currentTimeMillis();
        List<CyclingYellowCar> removeList = cyclingEndCarList.stream().filter(item -> item.getCyclingEndTime() >= currentTime).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(removeList)) {
            //增加目的站点的小黄车数量
            removeList.stream().forEach(item -> {
                String stationName = item.getEndStationName();
                Boolean addflag = stationApi.addByStationName(stationName, 1);
                if (addflag) {
                    //从存储的骑行中的car中移除记录
                    yellowCarApi.removeCyclingCar(item);
                }
            });
        }
    }

    private Station getStation(Station initStation) {
        for (; ; ) {
            Station station = stationApi.getRandomStation();
            if (station != null && initStation == null) {
                return station;
            }
            if (station != null && !initStation.getStationName().equals(station.getStationName())) {
                return station;
            }
        }
    }
}
